package org.dru.clay.respository.transport.ssh;

import java.io.Console;
import java.io.File;

public class ConsoleUserInfo implements SshUserInfo {
	private static final String TITLE = "JsClay SSH Transport";
	
	private String password;
	private String passphrase;
	private String username;
	private String identity;

	private boolean headerShown = false;
	
	@Override
	public String getPassphrase() {
		return passphrase;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public void setUsername(String username) {
		this.username = username;
	}
	
	@Override
	public String getIdentity() {
		return identity;
	}

	@Override
	public boolean promptPassphrase(String message) {
		final Console console = System.console();
		showHeader(console);
		passphrase = new String(console.readPassword("# %s: ", message));
		return passphrase.length() > 0;
	}

	@Override
	public boolean promptPassword(String message) {
		final Console console = System.console();
		showHeader(console);
		password = new String(console.readPassword("# %s: ", message));
		return password.length() > 0;		
	}
	
	@Override
	public boolean promptUsername(String message) {
		final Console console = System.console();
		showHeader(console);
		username = console.readLine("# %s: ", message);
		return username.length() > 0;		
	}	

	@Override
	public boolean promptYesNo(String message) {
		final Console console = System.console();
		showHeader(console);
		
		String line;
		while (true) {
			line = console.readLine("# %s [yes/no]: ", message);
			if ("yes".equalsIgnoreCase(line) || "y".equalsIgnoreCase(line)) {
				return true;
			}
			if ("no".equalsIgnoreCase(line) || "n".equalsIgnoreCase(line)) {
				return false;
			}
			console.printf("# ERROR: Please answer yes or no\n#\n");
		}
	}
	
	@Override
	public boolean promptForIdentity(String message) {
		final Console console = System.console();
		showHeader(console);
		
		final String line = console.readLine("# %s [~/.ssh/id_pub]: ", message);
		final File home = new File(System.getProperty("java.home"));
		
		if (line == null || line.length() == 0) {
			identity = new File(home, ".ssh/id_pub").getAbsolutePath();
			return true;
		}
		
		if (line.startsWith("~")) {
			identity = new File(home, line.substring(1)).getAbsolutePath();
			return true;
		}
		
		identity = line;		
		return true;
	}

	@Override
	public void showMessage(String message) {
		final Console console = System.console();
		showHeader(console);
		console.printf("# %s\n#\n", message);
	}
	
	private void showHeader(Console console) {
		if (headerShown) {
			return;
		}
		headerShown = true;
		console.printf("#\n# %s\n#\n", TITLE);
	}
}
